﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.Framework;
using WebAppAuthAdmin.Code;
using AuthApi.Contracts;
using WebAppAuthAdmin.Code.Security;

namespace WebAppAuthAdmin.App
{
    public partial class UserViewApplications : BasePage
    {

        // Faltan comandos de bloquear general, cambiar la password

        private UserWithApplication UserWithApplication
        {
            get
            {
                return (UserWithApplication)this.ViewState["UserWithApplication"];
            }
            set
            {
                this.ViewState["UserWithApplication"] = value;
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            LinkButton bloquearButton = new LinkButton();
            bloquearButton.ID = "bloquearTodos";
            bloquearButton.Text = "Bloquear En Todas las Aplicaciones";
            bloquearButton.Click += new EventHandler(lnkBloquearEnTodasLasAplicaciones_Click);
            actionButtons.Add(bloquearButton);

            bloquearButton = new LinkButton();
            bloquearButton.ID = "desbloquearTodos";
            bloquearButton.Text = "Desbloquear En Todas las Aplicaciones";
            bloquearButton.Click += new EventHandler(lnkDesBloquearEnTodasLasAplicaciones_Click);
            actionButtons.Add(bloquearButton);

            bloquearButton = new LinkButton();
            bloquearButton.ID = "cambiarPassword";
            bloquearButton.Text = "Cambiar Password";
            bloquearButton.Click += new EventHandler(lnkCambiarPassword_Click);
            actionButtons.Add(bloquearButton);

            LinkButton resetearPasswordButton = new LinkButton();
            resetearPasswordButton.ID = "resetPassword";
            resetearPasswordButton.Text = "Blanquear Password";
            resetearPasswordButton.Click += new EventHandler(lnkBlanquearPassword_Click);
            actionButtons.Add(resetearPasswordButton);

            LinkButton eliminarButton = new LinkButton();
            eliminarButton.ID = "eliminarUsuario";
            eliminarButton.Text = "Eliminar Usuario";
            eliminarButton.OnClientClick = "return confirm('Esta seguro que desea eliminar al usuario de todas las aplicaciones?');";
            eliminarButton.Click += new EventHandler(lnkEliminarUsuario_Click);
            actionButtons.Add(eliminarButton);

            
            base.LoadContextActions(actionButtons);
        }

        protected override void ApplySecurity()
        {
            bool edit = HasPermissionFor(AppSecurity.APP_USER_EDIT);
            this.lnkGuardar.Visible = edit;

            bool block = HasPermissionFor(AppSecurity.APP_USER_BLOCK);
            actionButtons.Where(a => a.ID == "bloquearTodos").Single().Visible = block;
            actionButtons.Where(a => a.ID == "desbloquearTodos").Single().Visible = block;
            
            actionButtons.Where(a => a.ID == "eliminarUsuario").Single().Visible = HasPermissionFor(AppSecurity.APP_USER_DELETE);

            var changePassBtn = actionButtons.Where(a => a.ID == "cambiarPassword").Single();
            if (UserWithApplication.UserName != BaseWebPage.UserName)
            {
                changePassBtn.Visible = HasPermissionFor(AppSecurity.APP_CHANGE_PASSWORD);
            }
            else
            {
                changePassBtn.Visible = HasPermissionFor(AppSecurity.APP_CHANGE_MY_PASSWORD);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                HasPermissionToSeeMe(AppSecurity.APP_VIEW_ALL_USERS);
                if (!this.IsPostBack)
                {
                    string userName = this.Request.QueryString["UserName"];

                    if (!String.IsNullOrEmpty(userName))
                    {
                        UserWithApplication = WebServiceHelper.GetUserWithApplications(this.GetSingleContextCompany().Id, userName);

                        if (this.Request.QueryString["existente"] != null)
                        {
                            if (this.Request.QueryString["applicationId"] != null)
                            {
                                int applicationId = Convert.ToInt32(this.Request.QueryString["applicationId"]);
                                WebServiceHelper.IncluirUsuarioEnAplicacion(this.GetSingleContextCompany().Id, applicationId, UserWithApplication.UserName);
                                Refresh(UserWithApplication.UserName);
                                this.masterPage.ShowMessage("El usuario ya existía. Fue incluido en la aplicación. Asigne sus permisos.", WebMessageType.Notification);
                            }
                            else
                            {
                                this.masterPage.ShowMessage("El usuario ya estaba creado, por favor incluyalo en la aplicación desde la grilla de aplicaciones.", WebMessageType.Notification);
                            }
                        }

                        Bind();
                    }
                    else
                    {
                        this.masterPage.ShowMessage(string.Format("Debe propocionar el parámetro {0}", userName), WebMessageType.Error);
                    }                                      
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void Bind()
        {
            if (UserWithApplication != null)
            {
                this.txtNombreUsuario.Text = UserWithApplication.GivenName;
                this.txtUserName.Text = UserWithApplication.UserName;
                this.chkPasswordLocal.Checked = UserWithApplication.UsaPasswordLocal;

                GridUserApplication.DataSource = UserWithApplication.WebApplicationList;
                GridUserApplication.DataBind();
            }
        }

        private void Refresh(string userName)
        {
            UserWithApplication = WebServiceHelper.GetUserWithApplications(this.GetSingleContextCompany().Id, userName);
            Bind();
        }

        private int rowIncluido = 1;
        private int rowBloquear = 2;
        private int rowPermisos = 3;
        private bool? tmpBlockPermission = null;
        protected void GridUserApplication_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (!tmpBlockPermission.HasValue)
                {
                    tmpBlockPermission = HasPermissionFor(AppSecurity.APP_USER_BLOCK);
                }

                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    WebApplicationInfoIncluded application = (WebApplicationInfoIncluded)e.Row.DataItem;
                    bool userCreatePermission = HasPermissionFor(AppSecurity.APP_USER_CREATE + application.Id.ToString());

                    if (!HasPermissionFor(AppSecurity.APP_VIEW_USERS_ID_ + application.Id.ToString()))
                    {
                        e.Row.Visible = false; // Cells[0].Text = string.Empty;
                    }
                    else
                    {
                        LinkButton lnkIncluido = (LinkButton)e.Row.Cells[rowIncluido].FindControl("lnkRowIncluir");
                        lnkIncluido.CommandArgument = e.Row.RowIndex.ToString(); //application.Id.ToString();
                        CheckBox chkIncluido = (CheckBox)e.Row.Cells[rowIncluido].FindControl("chkSelectRowIncluido");
                        chkIncluido.Checked = application.IsIncluded;
                        chkIncluido.Enabled = false;
                        if (!application.IsIncluded)
                        {
                            lnkIncluido.Text = "Incluir";
                            lnkIncluido.Visible = userCreatePermission;
                        }
                        else
                        {
                            lnkIncluido.Visible = false;
                        }
                       
                        string blockText = application.IsUserBlocked ?  "Desbloquear" : "Bloquear";
                        LinkButton lnkBloquear = (LinkButton)e.Row.Cells[rowBloquear].FindControl("lnkRowBloquear");
                        lnkBloquear.CommandArgument = e.Row.RowIndex.ToString();//application.Id.ToString();
                        lnkBloquear.Text = blockText;
                        CheckBox chkBloqueado = (CheckBox)e.Row.Cells[rowBloquear].FindControl("chkSelectRowBloqueado");
                        chkBloqueado.Checked = application.IsUserBlocked;
                        chkBloqueado.Enabled = false;

                        lnkBloquear.Visible = tmpBlockPermission.Value;

                        LinkButton lnkRowPermisos = (LinkButton)e.Row.Cells[rowPermisos].FindControl("lnkRowPermisos");
                        lnkRowPermisos.CommandArgument = e.Row.RowIndex.ToString();//application.Id.ToString();                        
                        lnkRowPermisos.Visible = HasPermissionFor(AppSecurity.APP_USERS_VIEWPERMISSION_ + application.Id.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridUserApplication_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName == "editar")
                {
                    int appId = Convert.ToInt32(this.GridUserApplication.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format("/App/UserEdit.aspx?UserName={0}&Application={1}&Company={2}", this.txtUserName.Text, appId, this.GetSingleContextCompany().Id), true);
                }
                else if (e.CommandName == "incluir")
                {
                    int appId = Convert.ToInt32(this.GridUserApplication.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);                    
                    // Incluir usuario en aplicacion
                    WebServiceHelper.IncluirUsuarioEnAplicacion(this.GetSingleContextCompany().Id, appId, UserWithApplication.UserName);
                    Refresh(UserWithApplication.UserName);
                }
                else if (e.CommandName == "bloquear")
                {
                    int appId = Convert.ToInt32(this.GridUserApplication.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);                    
                    // Bloquear usuario en aplicación
                    var app = UserWithApplication.WebApplicationList.Where(a => a.Id == appId).Single();
                    WebServiceHelper.BloquearUsuario(this.GetSingleContextCompany().Id, appId, UserWithApplication.UserName, !app.IsUserBlocked);
                    Refresh(UserWithApplication.UserName);
                }
                else if (e.CommandName == "permisos")
                {
                    int appId = Convert.ToInt32(this.GridUserApplication.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                    this.Response.Redirect(string.Format("/App/UserEditRole.aspx?UserName={0}&applicationId={1}&Company={2}", this.txtUserName.Text, appId, this.GetSingleContextCompany().Id), true);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                AdUser adUser = new AdUser();
                adUser.UserName = UserWithApplication.UserName;
                adUser.GivenName = this.txtNombreUsuario.Text;

                WebServiceHelper.SaveAppUser(adUser);

                this.masterPage.ShowMessage("Los datos se guardaron con éxito", WebMessageType.Notification);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkBloquearEnTodasLasAplicaciones_Click(object sender, EventArgs e)
        {
            BloquearSwitchTodos(true);
        }

        protected void lnkDesBloquearEnTodasLasAplicaciones_Click(object sender, EventArgs e)
        {
            BloquearSwitchTodos(false);
        }

        protected void lnkCambiarPassword_Click(object sender, EventArgs e)
        {
            try
            {
                this.Response.Redirect(string.Format("/App/CambiarPassword.aspx?UserName={0}", this.UserWithApplication.UserName), true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkBlanquearPassword_Click(object sender, EventArgs e)
        {
            try
            {                
                if (WebServiceHelper.ResetPassword(UserWithApplication.UserName))
                {
                    this.masterPage.ShowMessage("El password fue blanqueado con éxito.", WebMessageType.Notification);
                }
                else
                {
                    this.masterPage.ShowMessage("El password NO fue blanqueado con éxito.", WebMessageType.Warning);
                }

                Bind();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkEliminarUsuario_Click(object sender, EventArgs e)
        {
            try
            {
                WebServiceHelper.DeleteUser(UserWithApplication.UserName);
                this.Response.Redirect("/App/UserList.aspx", true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void BloquearSwitchTodos(bool bloquear)
        {
            try
            {
                // Bloquear usuario en aplicación
                var appIdList = UserWithApplication.WebApplicationList.Select(a => a.Id).ToList();
                foreach (var appId in appIdList)
                {
                    WebServiceHelper.BloquearUsuario(this.GetSingleContextCompany().Id, appId, UserWithApplication.UserName, bloquear);
                }

                Refresh(UserWithApplication.UserName);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}